package algorithm_demo.demo01;

import java.util.Arrays;
import java.util.Comparator;

/**
 * 比较器
 *
 * @author Api
 * @date 2023/2/1 22:16
 */
public class Code21_ShowComparator {


    public static class Student {
        private String name;
        private int id;
        private int age;

        public Student(String name, int id, int age) {
            this.name = name;
            this.id = id;
            this.age = age;
        }
    }

    //谁id大，谁放前
    public static class IdComparator implements Comparator<Student> {
        //如果返回负数，认为第一个参数应该排在前面
        //如果返回正数，认为第二个参数应该排在前面
        //如果返回0，认为谁放前面无所谓
        @Override
        public int compare(Student o1, Student o2) {
            return Integer.compare(o2.id, o1.id);
        }
    }

    public static void printStudents(Student[] students) {
        for (Student student : students) {
            System.out.println(student.name + ", " + student.id + ", " + student.age);
        }
    }

    public static void main(String[] args) {
        Student s1 = new Student("张三", 5, 27);
        Student s2 = new Student("李四", 1, 17);
        Student s3 = new Student("王五", 4, 29);
        Student s4 = new Student("赵六", 3, 9);
        Student s5 = new Student("左七", 2, 34);
        Student[] students = { s1, s2, s3, s4, s5 };
        Arrays.sort(students, new IdComparator());
        printStudents(students);
    }
}
